package com.lry.sso.gateway.bean;

import javax.servlet.ServletOutputStream;
import javax.servlet.WriteListener;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpServletResponseWrapper;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;

/**
 * 响应封装类
 *
 * @author 李瑞益
 * @date 2019/11/17
 */
@SuppressWarnings("unchecked")
public class ResponseWrapper extends HttpServletResponseWrapper  {
    private ByteArrayOutputStream byteArrayOut;
    private ServletOutputStream servletOut;
    private PrintWriter printWriter = null;

    public ResponseWrapper(HttpServletResponse response) {
        super(response);
        //真正存储数据的流
        byteArrayOut = new ByteArrayOutputStream();
        servletOut = new WrapperOutputStream(byteArrayOut);
    }

    @Override
    public ServletOutputStream getOutputStream() throws IOException {
        return servletOut;
    }

    @Override
    public PrintWriter getWriter() throws IOException {
        printWriter = new PrintWriter(new OutputStreamWriter(byteArrayOut,this.getCharacterEncoding()));
        return  printWriter;
    }

    @Override
    public void flushBuffer() throws IOException {
        if (byteArrayOut != null) {
            byteArrayOut.flush();
        }
        if (printWriter != null) {
            printWriter.flush();
        }
    }


    public byte[] toByteArray() throws IOException {
        //将out、writer中的数据强制输出到WapperedResponse的buffer里面，否则取不到数据
        flushBuffer();
        return byteArrayOut.toByteArray();
    }

    /**
     *内部类，对ServletOutputStream进行包装
     *
     * @author 李瑞益
     * @date 2019/11/24
     */
    private static class WrapperOutputStream extends  ServletOutputStream {

        private ByteArrayOutputStream bos;

        public WrapperOutputStream(ByteArrayOutputStream outputStream) {
            this.bos = outputStream;
        }
        @Override
        public boolean isReady() {
            return false;
        }

        @Override
        public void setWriteListener(WriteListener writeListener) {

        }

        @Override
        public void write(int b) throws IOException {
            bos.write(b);
        }
    }
}
